"use client"

import React, { useState, useEffect } from 'react'
import { AdminLayout } from '@/components/layout/admin-layout'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Modal } from '@/components/ui/modal'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  UserCog,
  UserPlus,
  Search,
  RefreshCw,
  Eye,
  Edit,
  Key,
  Shield,
  Ban,
  CheckCircle
} from 'lucide-react'
import { adminAPI, type Admin } from '@/lib/api'
import { formatDateTime } from '@/lib/utils'
import { CompletePagination } from '@/components/ui/pagination'
import { useToast } from '@/components/ui/toast'
import { useConfirm } from '@/components/ui/confirm'
import { usePrompt } from '@/components/ui/prompt'

export default function AdminsPage() {
  const [admins, setAdmins] = useState<Admin[]>([])
  const [loading, setLoading] = useState(true)
  const toast = useToast()
  const confirm = useConfirm()
  const prompt = usePrompt()
  const [searchTerm, setSearchTerm] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)

  // 添加管理员模态框状态
  const [showAddModal, setShowAddModal] = useState(false)
  const [addAdminForm, setAddAdminForm] = useState({
    username: '',
    password: '',
    email: '',
    nickname: ''
  })
  const [submitting, setSubmitting] = useState(false)

  // 查看和编辑管理员模态框状态
  const [showViewModal, setShowViewModal] = useState(false)
  const [showEditModal, setShowEditModal] = useState(false)
  const [selectedAdmin, setSelectedAdmin] = useState<Admin | null>(null)
  const [editAdminForm, setEditAdminForm] = useState({
    username: '',
    email: '',
    nickname: '',
    status: 1
  })

  useEffect(() => {
    const loadAdmins = async () => {
      try {
        const adminsData = await adminAPI.getAllAdmins()
        setAdmins(adminsData)
      } catch (error) {
        console.error('加载管理员失败:', error)
      } finally {
        setLoading(false)
      }
    }

    loadAdmins()
  }, [])

  const filteredAdmins = admins.filter(admin => 
    admin.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
    (admin.email && admin.email.toLowerCase().includes(searchTerm.toLowerCase())) ||
    (admin.nickname && admin.nickname.toLowerCase().includes(searchTerm.toLowerCase()))
  )

  // 分页计算
  const totalItems = filteredAdmins.length
  const totalPages = Math.ceil(totalItems / pageSize)
  const startIndex = (currentPage - 1) * pageSize
  const endIndex = startIndex + pageSize
  const paginatedAdmins = filteredAdmins.slice(startIndex, endIndex)

  // 重置搜索时回到第一页
  useEffect(() => {
    setCurrentPage(1)
  }, [searchTerm])

  const handlePageChange = (page: number) => {
    setCurrentPage(page)
  }

  const handlePageSizeChange = (size: number) => {
    setPageSize(size)
    setCurrentPage(1)
  }

  // 处理管理员操作（查看、编辑、禁用/启用、重置密码）
  const handleAdminAction = async (action: string, adminId: number) => {
    try {
      if (action === '查看') {
        const admin = await adminAPI.getAdminById(adminId)
        setSelectedAdmin(admin)
        setShowViewModal(true)
      } else if (action === '编辑') {
        const admin = await adminAPI.getAdminById(adminId)
        setSelectedAdmin(admin)
        setEditAdminForm({
          username: admin.username,
          email: admin.email || '',
          nickname: admin.nickname || '',
          status: admin.status
        })
        setShowEditModal(true)
      } else if (action === '禁用' || action === '启用') {
        const newStatus = action === '启用' ? 1 : 0
        const confirmed = await confirm({
          title: `确认${action}管理员`,
          message: `确认${action}这个管理员吗？`,
          type: action === '禁用' ? 'warning' : 'info',
          confirmText: action,
          cancelText: '取消'
        })
        
        if (confirmed) {
          await adminAPI.updateAdminStatus(adminId, newStatus)
          // 重新加载管理员列表
          const adminsData = await adminAPI.getAllAdmins()
          setAdmins(adminsData)
          toast.success(`管理员${action}成功！`)
        }
      } else if (action === '重置密码') {
        const newPassword = await prompt({
          title: '重置管理员密码',
          message: '请输入新密码：',
          defaultValue: '123456',
          placeholder: '请输入新密码',
          type: 'password',
          confirmText: '重置',
          cancelText: '取消'
        })
        
        if (newPassword) {
          // 这里需要实现重置密码的API，暂时先显示提示
          toast.success(`管理员密码已重置为：${newPassword}`)
        }
      }
    } catch (error) {
      console.error(`${action}管理员失败:`, error)
      toast.error(`${action}管理员失败，请重试`)
    }
  }

  // 处理添加管理员表单变化
  const handleFormChange = (field: string, value: string) => {
    setAddAdminForm(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // 处理编辑管理员表单变化
  const handleEditFormChange = (field: string, value: string | number) => {
    setEditAdminForm(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // 重置表单
  const resetForm = () => {
    setAddAdminForm({
      username: '',
      password: '',
      email: '',
      nickname: ''
    })
  }

  // 重置编辑表单
  const resetEditForm = () => {
    setEditAdminForm({
      username: '',
      email: '',
      nickname: '',
      status: 1
    })
  }

  // 处理添加管理员
  const handleAddAdmin = async () => {
    if (!addAdminForm.username || !addAdminForm.password) {
      toast.warning('请填写必填字段：用户名、密码')
      return
    }

    setSubmitting(true)
    try {
      // 调用API添加管理员
      await adminAPI.createAdmin(addAdminForm)
      
      // 成功后重新加载管理员列表
      const adminsData = await adminAPI.getAllAdmins()
      setAdmins(adminsData)
      
      // 关闭模态框并重置表单
      setShowAddModal(false)
      resetForm()
      
      toast.success('管理员添加成功！')
    } catch (error) {
      console.error('添加管理员失败:', error)
      toast.error('添加管理员失败，请重试')
    } finally {
      setSubmitting(false)
    }
  }

  // 处理编辑管理员
  const handleEditAdmin = async () => {
    if (!editAdminForm.username) {
      toast.warning('请填写必填字段：用户名')
      return
    }

    if (!selectedAdmin) return

    setSubmitting(true)
    try {
      // 调用API更新管理员
      await adminAPI.updateAdmin(selectedAdmin.id, editAdminForm)
      
      // 重新加载管理员列表
      const adminsData = await adminAPI.getAllAdmins()
      setAdmins(adminsData)
      
      // 关闭模态框并重置表单
      setShowEditModal(false)
      resetEditForm()
      setSelectedAdmin(null)
      
      toast.success('管理员更新成功！')
    } catch (error) {
      console.error('更新管理员失败:', error)
      toast.error('更新管理员失败，请重试')
    } finally {
      setSubmitting(false)
    }
  }

  if (loading) {
    return (
      <AdminLayout>
        <div className="space-y-6">
          <div className="flex items-center justify-between">
            <h1 className="text-2xl font-bold text-gray-900">管理员管理</h1>
          </div>
          <div className="text-center py-12">加载中...</div>
        </div>
      </AdminLayout>
    )
  }

  return (
    <AdminLayout>
      <div className="space-y-6">
        {/* Page Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">管理员管理</h1>
            <p className="text-gray-600">管理系统管理员账户和权限</p>
          </div>
          <Button onClick={() => setShowAddModal(true)}>
            <UserPlus className="h-4 w-4 mr-2" />
            添加管理员
          </Button>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">管理员总数</p>
                  <p className="text-2xl font-bold text-gray-900">{admins.length}</p>
                </div>
                <UserCog className="h-8 w-8 text-blue-600" />
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">活跃管理员</p>
                  <p className="text-2xl font-bold text-gray-900">
                    {admins.filter(a => a.status === 1).length}
                  </p>
                </div>
                <div className="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                  <CheckCircle className="h-5 w-5 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">禁用管理员</p>
                  <p className="text-2xl font-bold text-gray-900">
                    {admins.filter(a => a.status === 0).length}
                  </p>
                </div>
                <div className="w-8 h-8 bg-red-100 rounded-full flex items-center justify-center">
                  <Ban className="h-5 w-5 text-red-600" />
                </div>
              </div>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-gray-600">近期活跃</p>
                  <p className="text-2xl font-bold text-gray-900">
                    {admins.filter(a => a.lastLoginTime && 
                      (new Date().getTime() - new Date(a.lastLoginTime).getTime()) < 7 * 24 * 60 * 60 * 1000
                    ).length}
                  </p>
                </div>
                <div className="w-8 h-8 bg-amber-100 rounded-full flex items-center justify-center">
                  <Shield className="h-5 w-5 text-amber-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Search and Actions */}
        <Card>
          <CardContent className="p-6">
            <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
              <div className="relative flex-1 max-w-sm">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                <input
                  type="text"
                  placeholder="搜索管理员..."
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
              <Button variant="outline" size="sm" onClick={() => window.location.reload()}>
                <RefreshCw className="h-4 w-4 mr-2" />
                刷新
              </Button>
            </div>
          </CardContent>
        </Card>

        {/* Admins Table */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <UserCog className="h-5 w-5" />
                <span>管理员列表 ({filteredAdmins.length})</span>
              </div>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>管理员信息</TableHead>
                  <TableHead>联系方式</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>登录统计</TableHead>
                  <TableHead>最后登录</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {paginatedAdmins.length > 0 ? (
                  paginatedAdmins.map((admin) => (
                    <TableRow key={admin.id}>
                      <TableCell>
                        <div className="flex items-center space-x-3">
                          <div className="w-10 h-10 bg-slate-600 text-white rounded-full flex items-center justify-center">
                            <UserCog className="h-5 w-5" />
                          </div>
                          <div>
                            <div className="font-medium text-gray-900">{admin.username}</div>
                            <div className="text-sm text-gray-500">ID: {admin.id}</div>
                            {admin.nickname && (
                              <div className="text-sm text-gray-500">{admin.nickname}</div>
                            )}
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm">
                          {admin.email ? (
                            <div>{admin.email}</div>
                          ) : (
                            <div className="text-gray-400">未设置邮箱</div>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant={admin.status === 1 ? 'default' : 'destructive'}
                          className={admin.status === 1 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}
                        >
                          {admin.status === 1 ? '正常' : '禁用'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm text-gray-600">
                          {admin.loginCount} 次登录
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm text-gray-600">
                          {admin.lastLoginTime 
                            ? formatDateTime(admin.lastLoginTime)
                            : '从未登录'
                          }
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm text-gray-600">
                          {formatDateTime(admin.createdAt)}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleAdminAction('查看', admin.id)}
                            title="查看详情"
                          >
                            <Eye className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleAdminAction('编辑', admin.id)}
                            title="编辑"
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          {admin.id !== 1 && (
                            <>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleAdminAction('重置密码', admin.id)}
                                title="重置密码"
                              >
                                <Key className="h-4 w-4 text-blue-600" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleAdminAction(
                                  admin.status === 1 ? '禁用' : '启用', 
                                  admin.id
                                )}
                                title={admin.status === 1 ? '禁用账户' : '启用账户'}
                              >
                                {admin.status === 1 ? (
                                  <Ban className="h-4 w-4 text-red-600" />
                                ) : (
                                  <CheckCircle className="h-4 w-4 text-green-600" />
                                )}
                              </Button>
                            </>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-8">
                      <div className="text-gray-500">
                        {searchTerm ? '没有找到匹配的管理员' : '暂无管理员数据'}
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </CardContent>
        </Card>

        {/* Pagination */}
        {totalItems > 0 && (
          <Card>
            <CardContent className="p-6">
              <CompletePagination
                currentPage={currentPage}
                totalPages={totalPages}
                totalItems={totalItems}
                pageSize={pageSize}
                onPageChange={handlePageChange}
                onPageSizeChange={handlePageSizeChange}
                pageSizeOptions={[5, 10, 20, 50]}
              />
            </CardContent>
          </Card>
        )}

        {/* Add Admin Modal */}
        <Modal
          isOpen={showAddModal}
          onClose={() => {
            setShowAddModal(false)
            resetForm()
          }}
          title="添加新管理员"
          footer={
            <div className="flex justify-end space-x-2">
              <Button 
                variant="outline" 
                onClick={() => {
                  setShowAddModal(false)
                  resetForm()
                }}
                disabled={submitting}
              >
                取消
              </Button>
              <Button 
                onClick={handleAddAdmin}
                disabled={submitting}
              >
                {submitting ? '添加中...' : '添加管理员'}
              </Button>
            </div>
          }
        >
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                用户名 <span className="text-red-500">*</span>
              </label>
              <Input
                value={addAdminForm.username}
                onChange={(e) => handleFormChange('username', e.target.value)}
                placeholder="请输入管理员用户名"
                disabled={submitting}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                密码 <span className="text-red-500">*</span>
              </label>
              <Input
                type="password"
                value={addAdminForm.password}
                onChange={(e) => handleFormChange('password', e.target.value)}
                placeholder="请输入密码"
                disabled={submitting}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                邮箱
              </label>
              <Input
                type="email"
                value={addAdminForm.email}
                onChange={(e) => handleFormChange('email', e.target.value)}
                placeholder="请输入邮箱地址（可选）"
                disabled={submitting}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                昵称
              </label>
              <Input
                value={addAdminForm.nickname}
                onChange={(e) => handleFormChange('nickname', e.target.value)}
                placeholder="请输入昵称（可选）"
                disabled={submitting}
              />
            </div>
          </div>
        </Modal>

        {/* View Admin Modal */}
        <Modal
          isOpen={showViewModal}
          onClose={() => {
            setShowViewModal(false)
            setSelectedAdmin(null)
          }}
          title="查看管理员详情"
          footer={
            <div className="flex justify-end">
              <Button onClick={() => setShowViewModal(false)}>关闭</Button>
            </div>
          }
        >
          {selectedAdmin && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">管理员ID</label>
                  <div className="text-sm text-gray-900">{selectedAdmin.id}</div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                  <div className="text-sm text-gray-900">{selectedAdmin.username}</div>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                  <div className="text-sm text-gray-900">{selectedAdmin.email || '未设置'}</div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">昵称</label>
                  <div className="text-sm text-gray-900">{selectedAdmin.nickname || '未设置'}</div>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">状态</label>
                  <div className="text-sm">
                    <Badge
                      variant={selectedAdmin.status === 1 ? 'default' : 'destructive'}
                      className={selectedAdmin.status === 1 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}
                    >
                      {selectedAdmin.status === 1 ? '正常' : '禁用'}
                    </Badge>
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">登录次数</label>
                  <div className="text-sm text-gray-900">{selectedAdmin.loginCount} 次</div>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">创建时间</label>
                  <div className="text-sm text-gray-900">{formatDateTime(selectedAdmin.createdAt)}</div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">最后登录</label>
                  <div className="text-sm text-gray-900">
                    {selectedAdmin.lastLoginTime ? formatDateTime(selectedAdmin.lastLoginTime) : '从未登录'}
                  </div>
                </div>
              </div>
            </div>
          )}
        </Modal>

        {/* Edit Admin Modal */}
        <Modal
          isOpen={showEditModal}
          onClose={() => {
            setShowEditModal(false)
            resetEditForm()
            setSelectedAdmin(null)
          }}
          title="编辑管理员"
          footer={
            <div className="flex justify-end space-x-2">
              <Button 
                variant="outline" 
                onClick={() => {
                  setShowEditModal(false)
                  resetEditForm()
                  setSelectedAdmin(null)
                }}
                disabled={submitting}
              >
                取消
              </Button>
              <Button 
                onClick={handleEditAdmin}
                disabled={submitting}
              >
                {submitting ? '保存中...' : '保存更改'}
              </Button>
            </div>
          }
        >
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                用户名 <span className="text-red-500">*</span>
              </label>
              <Input
                value={editAdminForm.username}
                onChange={(e) => handleEditFormChange('username', e.target.value)}
                placeholder="请输入用户名"
                disabled={submitting}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                邮箱
              </label>
              <Input
                type="email"
                value={editAdminForm.email}
                onChange={(e) => handleEditFormChange('email', e.target.value)}
                placeholder="请输入邮箱地址"
                disabled={submitting}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                昵称
              </label>
              <Input
                value={editAdminForm.nickname}
                onChange={(e) => handleEditFormChange('nickname', e.target.value)}
                placeholder="请输入昵称"
                disabled={submitting}
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                状态
              </label>
              <select
                className="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-slate-500 focus:border-transparent"
                value={editAdminForm.status}
                onChange={(e) => handleEditFormChange('status', parseInt(e.target.value))}
                disabled={submitting}
              >
                <option value={1}>正常</option>
                <option value={0}>禁用</option>
              </select>
            </div>
          </div>
        </Modal>
      </div>
    </AdminLayout>
  )
}